package com.ccp.dev.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.PwdStrategyService;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.service.SysUserService;
import com.ccp.dev.system.service.UserPositionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用戶管理控制器类
 * @author  y
 */
@Controller
@Action(ownermodel = SysAuditModelType.USER_MANAGEMENT)
@RequestMapping(UrlConstants.PROJECT_ROOT+UrlConstants.PROJECT_MODULE_SYSTEM+"/sysUser")
public class SysUserController extends SysBaseController {
    @Resource
    SysUserService sysUserService;
    @Resource
    UserPositionService userPositionService;
    @Resource
    SysOrgService sysOrgService;
    @Resource
    PwdStrategyService pwdStrategyService;

    /**
     * 保存更新用户信息
     * @param sysUser 用户model
     * @return ResultData
     */
    @Action(description = "编辑用户信息",
            detail = "<#if StringUtil.isEmpty(userId)>添加<#else>更新</#if>用户【${userName}】<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    public ResultData add(HttpServletRequest request,@RequestBody SysUser sysUser) {
        SysAuditThreadLocalHolder.putParamerter("userId", sysUser.getUserId());
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            //2020-06-09 jyq新增密码策略验证
            String userId = sysUser.getUserId();
            if(StringUtil.isEmpty(userId)){
                String password = sysUser.getPassword();
                pwdStrategyService.checkStrategy(password);
            }
            //保存用户信息
            this.sysUserService.saveUser(sysUser);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("save.success");
        }catch (Exception e){
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg)?"save.failure":msg;
            SysAuditThreadLocalHolder.putParamerter("success", false);
            if(StringUtil.isNotEmpty(msg) && msg.contains(StringPool.UNDERSCORE)){
                String[] retArr = msg.split(StringPool.UNDERSCORE);
                return getResultDataErrorParam(retArr[0],new String[]{retArr[1]});
            }
            return getResultDataError(msg);
        }
    }

    /**
     * 删除用户信息
     * @param request HttpServletRequest
     * @return ResultData
     */
    @Action(description = "删除用户信息",
            detail = "删除用户<#list fullName as item>【${item}】</#list><#if success>成功<#else>失败</#if>",
            exectype = "删除日志")
    @ResponseBody
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    public ResultData delByIds(HttpServletRequest request) {
            String[] lAryId = RequestUtil.getStringAryByStr(request, "userId");
            SysAuditThreadLocalHolder.putParamerter("fullName",sysUserService.queryUserNameByUserIds(lAryId));
        try {
            sysUserService.delUserByIds(lAryId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("delete.success");
        }catch (Exception e){
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg)?"delete.failure":msg;
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError(msg);
        }
    }

    /**
     * 设置领导
     * @param request HttpServletRequest
     * @return ResultData
     */
    @Action(description = "用户置为领导",
            detail = "用户<#list fullName as item>【${item}】置为领导</#list><#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/setLeader")
    public ResultData setLeaderByIds(HttpServletRequest request) {
        String[] lAryId = RequestUtil.getStringAryByStr(request, "userId");
        SysAuditThreadLocalHolder.putParamerter("fullName",sysUserService.queryUserNameByUserIds(lAryId));
        try {
            sysUserService.setLeaderByIds(lAryId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg)?"operation.failure":msg;
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError(msg);
        }
    }

    /**
     * 取消领导
     * @param request HttpServletRequest
     * @return ResultData
     */
    @Action(description = "用户取消领导",
            detail = "用户设置领导取消<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/delLeader")
    public ResultData delLeader(HttpServletRequest request) {
        String userId = RequestUtil.getString(request, "userId");
        try {
            sysUserService.delLeader(userId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg)?"operation.failure":msg;
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError(msg);
        }
    }

    /**
     * 设置状态
     * @param sysUser 用户model
     * @return ResultData
     */
    @Action(description = "用户设置状态",
            detail = "设置用户【${userName}】状态<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/setupState")
    public ResultData setupState(@RequestBody SysUser sysUser) {
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            this.sysUserService.setupState(sysUser);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg)?"operation.failure":msg;
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError(msg);
        }
    }

    /**
     * 置为离线
     * @param userId 用户id
     * @return  ResultData
     */
    @Action(description = "将用户置为离线",
            detail = "将用户【${userName}】置为离线<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/setOffline")
    public ResultData setOffline(@RequestParam("userId") String userId){
        SysUser sysUser = this.sysUserService.getOneById(userId);
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            this.sysUserService.setOffline(userId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 重置密码
     * @param userId  用户id
     * @param password  密码
     * @return ResultData
     */
    @Action(description = "重置用户密码",
            detail = "重置用户【${userName}】密码<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/resetPwd")
    public ResultData resetPwd(@RequestParam("userId") String userId, @RequestParam("password") String password){
        SysUser sysUser = this.sysUserService.getOneById(userId);
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            this.sysUserService.resetPwd(userId,password);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            String msg = e.getMessage();
            if(StringUtil.isNotEmpty(msg) && msg.contains(StringPool.UNDERSCORE)){
                String[] retArr = msg.split(StringPool.UNDERSCORE);
                return getResultDataErrorParam(retArr[0],new String[]{retArr[1]});
            }
            msg = StringUtil.isEmpty(msg)?"operation.failure":msg;
            return getResultDataError(msg);
        }
    }
    /**
     * 修改密码
     * @param password  新密码
     * @param oldPassword 旧密码
     * @return ResultData
     */
    @Action(description = "修改用户密码",
            detail = "修改用户【${userName}】密码<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/modifyPwd")
    public ResultData modifyPwd(@RequestParam("password") String password, @RequestParam("oldPassword") String oldPassword){
        SysAuditThreadLocalHolder.putParamerter("userName", ContextUtil.getCurrentUser().getFullName());
        try {
            this.sysUserService.modifyPwd(ContextUtil.getCurrentUserId(),password,oldPassword);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            String msg = e.getMessage();
            if(StringUtil.isNotEmpty(msg) && msg.contains(StringPool.UNDERSCORE)){
                String[] retArr = msg.split(StringPool.UNDERSCORE);
                return getResultDataErrorParam(retArr[0],new String[]{retArr[1]});
            }
            msg = StringUtil.isEmpty(msg)?"operation.failure":msg;
            return getResultDataError(msg);
        }
    }

    /**
     * 查询是否跨租户
     * @param userId  用户id
     * @param orgId   组织id
     * @return ResultData
     */
    @Action(description = "查询用户调整组织是否跨租户",
            detail = "查询用户【${userName}】租户<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @PostMapping("/searchIsStrideTenant")
    public ResultData searchIsStrideTenant(@RequestParam("userId") String userId,@RequestParam("oldOrgId") String oldOrgId,@RequestParam("orgId") String orgId){
        SysUser sysUser = this.sysUserService.getOneById(userId);
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            String oldTenantId = sysOrgService.getTenantIdByOrgId(oldOrgId);
            String tenantId = sysOrgService.getTenantIdByOrgId(orgId);
            boolean equals = tenantId.equals(oldTenantId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",equals);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 调换组织
     * @param userId  用户id
     * @param orgId   组织id
     * @return ResultData
     */
    @Action(description = "修改用户组织",
            detail = "修改用户【${userName}】组织<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/changeOrg")
    public ResultData changeOrg(@RequestParam("userId") String userId, @RequestParam("orgId") String orgId, @RequestParam("isKeep") int isKeep){
        SysUser sysUser = this.sysUserService.getOneById(userId);
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            this.userPositionService.updUserOrg(userId,orgId,isKeep);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg)?"operation.failure":msg;
            return getResultDataError(msg);
        }
    }

    /**
     * 取得用户表分页列表
     * @param request HttpServletRequest
     * @return ResultData
     */
    @Action(description = "查询用户列表",
            detail = "查询列表<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping(UrlConstants.MODULE_FUNCTION_LIST)
    public ResultData list(HttpServletRequest request) {
        try {
            String dataPrivacyLevelStr = request.getParameter("dataPrivacyLevel");
            QueryFilter queryFilter = new QueryFilter(request);
            if (StringUtil.isNotEmpty(dataPrivacyLevelStr)) {
                queryFilter.addFilter("dataPrivacyLevel",Integer.parseInt(dataPrivacyLevelStr));
            }
            List<SysUser> list = this.sysUserService.list(queryFilter);
            String currentUserId = ContextUtil.getCurrentUserId();
            for (SysUser user : list) {
                if (user.getUserId().equals(currentUserId)) {
                    user.setIsCurrent(SysUser.IS_CURRENT);
                }else{
                    user.setIsCurrent(SysUser.NOT_CURRENT);
                }
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 根据id获取用户信息
     * @param userId 用户id
     * @return ResultData
     */
    @Action(description = "查询用户信息",
            detail = "查询<#if success>【${userName}】信息成功<#else>信息失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping(UrlConstants.MODULE_FUNCTION_GET)
    public ResultData get(@RequestParam String userId){
        try {
            SysUser sysUser = this.sysUserService.getOneById(userId);
            if (sysUser == null) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return getResultDataError("sysUser.userInfo.emptyUser");
            }
            SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",0,sysUser);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 获取当前登录人信息
     * @return ResultData
     */
    @Action(description = "查询当前登录用户信息",
            detail = "查询<#if success>信息成功<#else>信息失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping("/getCurrentUser")
    public ResultData getCurrentUser(){
        try {
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            Map<String,Object> map = new HashMap<>(3);
            map.put("fullName",sysUser.getFullName());
            map.put("userId",sysUser.getUserId());
            /*
            modify by NiuDong
            组织管理 前端列表树需要顶级id
             */
            if(SystemConst.SUPER_ADMIN_ID.equals(sysUser.getUserId())){
                map.put("orgId",SystemConst.TOP_ORG_SUP_ID);
            }else{
                SysOrg orgTemp = sysOrgService.getOrgByUserId(ContextUtil.getCurrentUserId());
                map.put("orgId",orgTemp.getOrgSupId());
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",0,map);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 角色增加用户时用户选择器
     * @param request HttpServletRequest
     * @return ResultData
     */
    @Action(description = "角色增加用户时用户选择器查询列表",
            detail = "查询<#if success>信息成功<#else>信息失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping("/userSelectorQueryList")
    public ResultData userSelectorQueryList(HttpServletRequest request){
        try {
            QueryFilter queryFilter = new QueryFilter(request);
            List<SysUser> list = this.sysUserService.userSelectorQueryList(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 根据组织id查询用户
     * @param orgId 组织id
     * @return 用户列表
     */
    @Action(description = "根据组织id查询用户列表",
            detail = "查询<#if success>信息成功<#else>信息失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping("/queryUserListByOrgId")
    public List<SysUser> queryUserListByOrgId(@RequestParam String orgId) {
        return sysUserService.queryUserListByOrgId(orgId);
    }

    /**
     * 根据角色id查询用户
     * @param roleId 角色id
     * @return 用户列表
     */
    @Action(description = "根据角色id查询用户列表",
            detail = "查询<#if success>信息成功<#else>信息失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping("/queryUserListByRoleId")
    public List<SysUser> queryUserListByRoleId(@RequestParam String roleId) {
        return sysUserService.queryUserListByRoleId(roleId);
    }

    /**
     * 查询在线用户
     * @param request 查询条件（组织ID，用户ID）
     * @return 用户列表
     */
    @Action(description = "查询在线用户列表",
            detail = "查询<#if success>信息成功<#else>信息失败</#if>",
            exectype = "查询日志")
    @ResponseBody
    @GetMapping("/queryUserListByIsOnline")
    public ResultData queryUserListByIsOnline(HttpServletRequest request) {
        //获取当前用户ID
        String currentUserId = ContextUtil.getCurrentUserId();
        try {
            QueryFilter queryFilter = new QueryFilter(request);
            queryFilter.addFilter("isOnline",SysUser.ISONLINE_Y);
            //2020.03.25 新增逻辑：传值userId,实现查询时将当前用户信息排在第一位
            queryFilter.addFilter("currentUserId",currentUserId);
            List<SysUser> list = this.sysUserService.list(queryFilter);
            //判断list的第一个值是否为当前用户信息
            if (list.size()!=0 && list.get(0).getUserId().equals(currentUserId)) {
                list.get(0).setIsCurrent(SysUser.IS_CURRENT);
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",queryFilter.getPageBean().getTotalCount(),list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 页面跳转 列表页
     */
    @Action(description = "用户列表页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/online")
    public String viewOnLineList(){
        return "sysUser/online";
    }
    /**
     * 页面跳转 修改密码
     */
    @Action(description = "用户修改密码页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/resetPwd")
    public String viewResetPwd(HttpServletRequest request , Model model){
        String msg = RequestUtil.getString(request,"msg");
        if(StringUtil.isNotEmpty(msg)){
            msg = localeMessageSource.getMessage(msg);
        }
        model.addAttribute("msg",msg);
        return "user/password";
    }
    /**
     * 页面跳转 列表页
     */
    @Action(description = "用户列表页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/list")
    public String viewList(){
        return "sysUser/list";
    }
    /**
     * 页面跳转 新增/修改
     */
    @Action(description = "用户编辑页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/addEdit")
    public String viewAdd(HttpServletRequest request , Model model){
        String selectOrgId = RequestUtil.getString(request,"selectOrgId");
        String userId = RequestUtil.getString(request,"userId",null);
        model.addAttribute("selectOrgId",selectOrgId);
        model.addAttribute("userId",userId);
        model.addAttribute("picture","");
        if(StringUtil.isNotEmpty(userId)){
            SysUser sysUser = this.sysUserService.getOneById(userId);
            model.addAttribute("sysUser", JSONObject.toJSON(sysUser).toString());
            model.addAttribute("picture",sysUser.getPicture());
        }
        return "sysUser/addEdit";
    }
    /**
     * 页面跳转 查看
     */
    @Action(description = "用户详情页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/view")
    public String viewInfo(HttpServletRequest request , Model model){
        String userId = RequestUtil.getString(request,"userId");
        model.addAttribute("userId",userId);
        model.addAttribute("picture","");
        if(StringUtil.isNotEmpty(userId)){
            SysUser sysUser = this.sysUserService.getOneById(userId);
            model.addAttribute("picture",sysUser.getPicture());
        }
        return "sysUser/view";
    }
    /**
     * 页面跳转 设置状态
     */
    @Action(description = "用户设置状态页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/setStatus")
    public String viewSetStatus(HttpServletRequest request , Model model){
        String userId = RequestUtil.getString(request,"userId");
        model.addAttribute("userId",userId);
        return "sysUser/setStatus";
    }
    /**
     * 页面跳转 重置密码
     */
    @Action(description = "用户重置密码页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/ressetPass")
    public String viewRessetPass(HttpServletRequest request , Model model){
        String userId = RequestUtil.getString(request,"userId");
        model.addAttribute("userId",userId);
        return "sysUser/ressetPass";
    }
    /**
     * 页面跳转 下属管理
     */
    @Action(description = "用户下属管理页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/managementOfSub")
    public String viewManagementOfSub(HttpServletRequest request , Model model){
        String userId = RequestUtil.getString(request,"userId");
        model.addAttribute("userId",userId);
        return "sysUser/managementOfSub";
    }

    /**
     * 页面跳转 列表页
     */
    @Action(description = "用户列表页面跳转", exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/move")
    public String move(HttpServletRequest request, Model model) {
        String ids = RequestUtil.getString(request, "ids");
        model.addAttribute("ids", ids);
        return "sysUser/move";
    }

    /**
     * 用户批量导入
     */
    @ResponseBody
    @PostMapping("/impuserExcel")
    public ResultData impuserExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
        String preUrl = RequestUtil.getPrePage(request);
        String result = sysUserService.impuserExcel(file);
        return getResultDataSuccess("operation.success", result);
    }

    /**
     * 用户批量导出
     */
    @GetMapping("/outputExcelList")
    public void outputExcelList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        QueryFilter queryFilter = new QueryFilter(request);
//        String orgId = RequestUtil.getString(request,"orgId");
//        queryFilter.addFilter("orgId",orgId);
//        List<SysUser> list = this.userService.getImplist(queryFilter);
        //List<SysUser> list = this.userService.queryPosUsersByuserId(ContextUtil.getCurrentUserId());

        QueryFilter queryFilter = new QueryFilter(request);
        List<SysUser> list = this.sysUserService.list(queryFilter);

        ByteArrayOutputStream outputExcel = sysUserService.outputExcel(list);
        byte[] content = outputExcel.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        String tempFileName = "用户信息.xls";
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((tempFileName).getBytes("utf-8"), "iso-8859-1"));


        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            e.printStackTrace();
            //System.out.println("导出失败！！！");
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
            if (outputExcel != null)
                outputExcel.close();
        }
    }

    /**
     * 移动用户所属组织
     *
     * @param request HttpServletRequest
     * @return ResultData
     */
    @Action(description = "移动用户所属组织",
            detail = "移动用户<#list fullName as item>【${item}】</#list><#if success>成功<#else>失败</#if>",
            exectype = "移动用户日志")
    @ResponseBody
    @PostMapping("/move")
    public ResultData move(HttpServletRequest request) {
        String[] lAryId = RequestUtil.getStringAryByStr(request, "userIds");
        String orgId = RequestUtil.getString(request, "orgId");
        SysAuditThreadLocalHolder.putParamerter("fullName", sysUserService.queryUserNameByUserIds(lAryId));
        try {
            //userService.delUserByIds(lAryId);
            sysUserService.moveUser(lAryId, orgId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("update.success");
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            msg = StringUtil.isEmpty(msg) ? "update.failure" : msg;
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError(msg);
        }
    }

    /**
     * 设置用户排序
     *
     * @param userId     用户id
     * @param sortNumber 用户排序
     * @return ResultData
     */
    @Action(description = "设置用户排序",
            detail = "更改用户【${userName}】排序<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @ResponseBody
    @PostMapping("/updateSortNumber")
    public ResultData updateSortNumber(@RequestParam("userId") String userId, @RequestParam("sortNumber") Integer sortNumber) {
        SysUser sysUser = this.sysUserService.getOneById(userId);
        SysAuditThreadLocalHolder.putParamerter("userName", sysUser.getFullName());
        try {
            this.sysUserService.updateSortNumber(userId, sortNumber);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

}
